<!--历史数据-->
<template>
  <div class="ele-body">
    <!-- 搜索表单 -->
    <div class="block-interval">
      <a-card :bordered="false">
        <a-form layout="inline" :model="where">
          <a-row>
            <a-form-item label="开始时间:">
              <a-date-picker v-model:value="where.searchBeginTime" type="date" show-time format="YYYY-MM-DD" valueFormat="YYYY-MM-DD"/>
            </a-form-item>
            <a-form-item label="结束时间:">
              <a-date-picker v-model:value="where.searchEndTime" type="date" show-time format="YYYY-MM-DD" valueFormat="YYYY-MM-DD"/>
            </a-form-item>
            <a-form-item class="ele-text-center">
              <a-space>
                <a-button type="primary" @click="reload">查询</a-button>
                <a-button @click="reset">重置</a-button>
                <a-button @click="downloadFile">下载</a-button>
              </a-space>
            </a-form-item>

          </a-row>
        </a-form>
      </a-card>

      <a-card
        :bordered="false"
        :body-style="{padding: '16px 6px 0 0'}">
        <v-chart
          ref="ch4Chart"
          style="height: 362px;"
          :option="methaneChartOption"/>
      </a-card>
    </div>

    <!-- 表格 -->
    <div>
      <a-card :bordered="false">
        <ele-pro-table
          ref="table"
          row-key="liedtimeId"
          :datasource="datasource"
          :columns="columns"
          :where="where"
          :scroll="{ x: 'max-content' }"
        >
          <template #bodyCell="{ column, record }">
            <!-- table操作栏按钮 -->
            <template v-if="column.key === 'action'">
              <a-space>
                <a-popconfirm title="确定要删除此记录吗？" @confirm="remove(record)">
                  <a class="ele-text-danger">删除</a>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>

  </div>
</template>

<script>
import { provide } from 'vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart, BarChart } from 'echarts/charts';
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  DataZoomComponent
} from 'echarts/components';
import VChart, { THEME_KEY } from 'vue-echarts';
import 'echarts-wordcloud';
import { ChartTheme } from 'ele-admin-pro';
import {message} from 'ant-design-vue';
import {DeviceLiedownTimesApi} from "@/api/property/cattlesports/DeviceLiedownTimesApi";
import moment from "moment";
import {SysDatadownLogApi} from "@/api/system/operation/SysDatadownLogApi";

use([
  CanvasRenderer,
  LineChart,
  BarChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  DataZoomComponent
]);

provide(THEME_KEY, ChartTheme);

export default {
  name: 'CattleManagerCattleLiedownDaycalLietimedata',
  components: {
    VChart,
  },
  props: {
    data: Object
  },
  async mounted() {
    this.getNewData();
  },
  computed: {
    methaneChartOption(){
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        title: {
          text: '躺卧时长与温度的对比',
          left: "center",
        },
        legend: {
          data: ['躺卧时长(分)', '躺卧平均温度(℃)'],
          right: 20
        },
        xAxis: [
          {
            type: 'category',
            axisTick: {
              alignWithLabel: true
            },
            // prettier-ignore
            data: this.lieTimesData.map(d => d.time)
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '躺卧时长(分)',
            position: 'right',
            alignTicks: true,
            axisLine: {
              show: true,
              lineStyle: {
                color: '#5470C6'
              }
            },
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            name: '温度(℃)',
            position: 'left',
            alignTicks: true,
            axisLine: {
              show: true,
              lineStyle: {
                color: '#EE6666'
              }
            },
            axisLabel: {
              formatter: '{value} °C'
            }
          }
        ],
        series: [
          {
            name: '躺卧时长(分)',
            type: 'bar',
            data: this.lieTimesData.map(d => d.lieTime),
            yAxisIndex: 0,
            barWidth : 15
          },
          {
            name: '躺卧平均温度(℃)',
            type: 'line',
            data: this.lieTimesData.map(d => d.lieAvgTemp),
            yAxisIndex: 1,
          }
        ]
      }
    }
  },
  data() {
    return {
      // 表格列配置
      columns: [
        {
          title: '时间',
          dataIndex: 'calDate',
        },
        {
          title: '躺卧时长(分)',
          dataIndex: 'lieTime',
        },
        {
          title: '躺卧最小温度(℃)',
          dataIndex: 'lieMinTemp',
        },
        {
          title: '躺卧最大温度(℃)',
          dataIndex: 'lieMaxTemp',
        },
        {
          title: '躺卧平均温度(℃)',
          dataIndex: 'lieAvgTemp',
        }
      ],
      // 表格搜索条件
      where: {
        "cattleId": this.data.cattleId
      },
      // 当前编辑数据
      current : null,
      // 是否显示编辑弹窗
      showDetail : false,
      lieTimesData : []
   }
  },
  methods: {
    downloadFile () {
      if (this.where.searchBeginTime && this.where.searchEndTime) {
        let fromParam = {
          "searchBeginTime" : this.where.searchBeginTime,
          "searchEndTime" : this.where.searchEndTime,
          "thirdId" : this.data.cattleId,
        };
        let from = {
          "downName" : "奶牛id为"+this.data.cattleId+"的按天统计的躺卧数据",
          "downScene" : 10,
          "downCondition" : JSON.stringify(fromParam)
        };

        let result = SysDatadownLogApi.add(from);
        result
          .then(result1 => {
            message.success("添加下载任务成功，请移步到【数据下载】->【导出记录】查看")
          })
          .catch(() => {
          });
      } else {
        message.warn("请选择时间条件");
      }
    },
    getNewData() {
      let that = this;
      let params =  {
        "cattleId" : that.data.cattleId,
        "sortBy" : "ASC",
        "orderBy" : "cal_date",
        searchBeginTime : moment().subtract(7, 'days').format('YYYY-MM-DD'),
        searchEndTime : moment().format('YYYY-MM-DD'),
      };

      if (that.where.searchBeginTime && that.where.searchEndTime) {
        params.searchBeginTime = that.where.searchBeginTime;
        params.searchEndTime = that.where.searchEndTime;
      }

      DeviceLiedownTimesApi.list(params).then(result => {
        let rows = result.data || [];
        let _lieTimesData = [];
        if (rows && rows.length > 0) {
          rows.forEach(function(item) {
            let formatItem = {
              time : item.calDate,
              lieTime : item.lieTime,
              lieAvgTemp : item.lieAvgTemp
            };
            _lieTimesData.push(formatItem);
          });
        } else {
          _lieTimesData.push({
            time : moment().subtract(6, 'days').format('YYYYMMDD'),
            lieTime : 0,
            lieAvgTemp : 0,
          });
          _lieTimesData.push({
            time : moment().subtract(4, 'days').format('YYYYMMDD'),
            lieTime : 0,
            lieAvgTemp : 0,
          });
          _lieTimesData.push({
            time : moment().subtract(1, 'days').format('YYYYMMDD'),
            lieTime : 0,
            lieAvgTemp : 0,
          });
        }
        that.lieTimesData = _lieTimesData;
      });
    },
    /**
     * 搜索按钮
     *
     * @author cancan
     * @date 2022/03/05 14:48
     */
    reload() {
      this.selection = [];
      this.$refs.table.reload({page: 1});
      this.getNewData();
    }
    ,

    /**
     * 重置搜索
     *
     * @author cancan
     * @date 2022/03/05 14:48
     */
    reset() {
      this.where.cattleId = this.data.cattleId;
      this.where.searchBeginTime = '';
      this.where.searchEndTime = '';
      this.$nextTick(() => {
        this.reload();
      });
    }
    ,

    /**
     * 删除
     *
     * @author cancan
     * @date 2022/03/05 14:48
     */
    async remove(row) {
      const result = await DeviceLiedownTimesApi.delete({liedtimeId: row.liedtimeId});
      message.success(result.message);
      this.reload();
    }
    ,

    /**
     * 打开新增或编辑弹窗
     *
     * @author cancan
     * @date 2022/03/05 14:48
     */
    openDetail(row) {
      this.current = row;
      this.showDetail = true;
    },
    /**
     * 获取表格数据
     *
     * @author fengshuonan
     * @date 2022/5/8 15:18
     */
    datasource({page, limit, where, orders}) {
      return DeviceLiedownTimesApi.findPage({...where, ...orders, pageNo: page, pageSize: limit});
    },
    activated() {
      ['ch4Chart'].forEach((name) => {
        this.$refs[name].resize();
      });
    }
  }
};
</script>
